var ns6 = document.getElementById;
var changeTrack = null;
var shareSelectContent = "";
var ie5 = document.all && !window.opera
var ORDER_BY = "relevance";
var MAX_RESULTS = "30";
var results = new Array();
var topTracks = new Array();
var inbox = new Array();
var playedTrack = null;
var currPlaylist = null;
var addTrack = null;
var incomingTrack = null;
var shareTrack = null;
var tracks;
var switchSearchTab = false;
var addFirstResult = false;
var message = null;
var playlists = new Array();
var friends;
var isPreview = false;
var isPlaying = false;
var numNewIncomingTracks = 0;
var isLoading = false;
var firstLoad = true;

var params = { allowScriptAccess: "always", bgcolor: "#cccccc" };
var atts = { id: "myytplayer" };
swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer",
"youtubeVideo", "100%", "80%", "8", null, null, params, atts);

/* init the youtube player */
function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById("myytplayer");
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
    ytplayer.addEventListener("onError", "onPlayerError");
}

/* update local variabels and actions when a song is ended, played or paused */
function onytplayerStateChange(newState) {
	prefs = new gadgets.Prefs();
    if (newState == 0) {
    	isPlaying = false;
    	document.getElementById('timeBarTD').style.display = "none";
        playNextTrack();
        prefs.set("playing", "false");
        prefs.set("song", "");
    }
    if (newState == 1) {
    	isPlaying = true;
    	document.getElementById('timeBarTD').style.display = "block";
    	document.getElementById('playPause').src = "http://tau-iplayer.googlecode.com/files/pause.png";
    	prefs.set("playing", "true");
    }
    if (newState == 2) {
    	isPlaying = false;
    	document.getElementById('playPause').src = "http://tau-iplayer.googlecode.com/files/play.png";
    	prefs.set("playing", "false");
    	prefs.set("song", "false");
    }
}

/* show msg when a deleted song is played */
function onPlayerError(errorCode) {
	// the song does not exsists or just can't be played in iPlayer
	if(errorCode != 101 && errorCode != 150){
		return;
	}
   	lastDeletedTrack = playedTrack;
   	message = 'The song "' + printTrack(playedTrack) + '" has been deleted from YouTube';
   	displayFeedback();	
}

/* playing the previous track */
function playPrevTrack() {
    if ((tracks == null) || (isPreview)) return;
    if (document.getElementsByName('shuffel')[0].checked) {
        var randomTrack = tracks[Math.floor(Math.random() * tracks.length)];
        while (trackEqual(playedTrack, randomTrack)) {
            randomTrack = tracks[Math.floor(Math.random() * tracks.length)];
        }
        playTrack(randomTrack);
        return;
    }
    var repeat = document.getElementsByName('repeat')[0].checked;
    var i;
    for (i = 0; i < tracks.length; i++) {
        if (trackEqual(tracks[i], playedTrack)) {
            if (i == 0) { //playing the first song
                if (repeat) {
                    playedTrack(tracks[tracks.length - 1]);
                    return;
                } else {
                    return;
                }
            } else {
                playTrack(tracks[i - 1]);
                return;
            }
        }
    }
    playTrack(tracks[0]);
}

/* playing the next track */
function playNextTrack() {
    if ((tracks == null) || (isPreview)) return;
    if (document.getElementsByName('shuffel')[0].checked) {
        var randomTrack = tracks[Math.floor(Math.random() * tracks.length)];
        while (trackEqual(playedTrack, randomTrack)) {
            randomTrack = tracks[Math.floor(Math.random() * tracks.length)];
        }
        playTrack(randomTrack);
        return;
    }
    var repeat = document.getElementsByName('repeat')[0].checked;
    var i;
    var nextTrackId = 0;
    for (i = 0; i < tracks.length; i++) {
        if (trackEqual(tracks[i], playedTrack)) {
            if (i == tracks.length - 1) { // played the last song
                if (repeat) {
                    playTrack(tracks[0]);
                    return;
                } else {
                    return;
                }
            }
            nextTrackId = i + 1;
            playTrack(tracks[nextTrackId]);
            return;
        }
    }
    playTrack(tracks[0]);
}

/* load a video from youtube and play it */
function loadVideo(videoId, startSecond) {
    if (ytplayer) {
        ytplayer.loadVideoById(videoId, parseInt(startSecond));
    }
}

/* load video from youtube whithout playing it */
function cueVideo(videoId, startSecond) {
    if (ytplayer) {
        ytplayer.cueVideoById(videoId, parseInt(startSecond));
        setInterval(updateTimeInfo, 250);
    }
}

/* update the track info in the window */
function updateTimeInfo() {
    currTime = getCurrTime();
    if (currTime <= 0) currTime = 0;
    currTime = parseInt(currTime);
    currTimeStr = getTimeFormat(currTime);
    var timeDiv = document.getElementById('nowPlayingDurationTime');
    timeDiv.innerHTML = currTimeStr + " / " + displayDuration(playedTrack);
    handleTimeBar();
}

/* return the mm:ss time format */
function getTimeFormat(seconds){
	minutes = parseInt(seconds / 60);
	seconds = seconds % 60;
	minutesStr = new String(minutes);
	secondsStr = new String(seconds);
	while(minutesStr.length < 2){
		minutesStr = "0" + minutesStr;
	}
	while(secondsStr.length < 2){
		secondsStr = "0" + secondsStr;
	}
	time = minutesStr + ":" + secondsStr;
	return time;
}

/* cues the given track */
function cueTrack(track){
	cueVideo(track.id,0);
	document.getElementById('nowPlayingTitle').innerHTML = printTrack(track);
	document.getElementById('nowPlayingDurationTime').innerHTML = getTimeFormat(track.duration);
	playedTrack = track;
	setInterval(updateTimeInfo, 1000);
	handleHeight();
}

/* play the track for preview only */
function playPreviewTrack(track) {
    isPreview = true;
    playTrack(track);
}

/* play a track from a playlist */
function playNotPreviewTrack(track) {
    isPreview = false;
    playTrack(track);
    prefs = new gadgets.Prefs();
    prefs.set("song", track.title);
}

/* playing a track */
function playTrack(track) {
    loadVideo(track.id, 0);
    document.getElementById('nowPlayingTitle').innerHTML = printTrack(track);
    document.getElementById('nowPlayingDurationTime').innerHTML = getTimeFormat(track.duration);
    playedTrack = track;
    displayTrackChoice();
    setInterval(updateTimeInfo, 1000);
    handleHeight();
}

/* displays the duration of the track */
function displayDuration(track){
	return getTimeFormat(track.duration);
}

/* play the youtube player */
function play() {
	//if(playedTrack == null) return;
    if (ytplayer) {
        if((playedTrack == null) && (tracks != null) && (tracks[0] != null)){
        	playNotPreviewTrack(tracks[0]);
        }else{
        	ytplayer.playVideo();
        }
    }
}

/* pause the youtube player */
function pause() {
	if(playedTrack == null) return;
    if (ytplayer) {
        ytplayer.pauseVideo();
    }
}

/* stop the youtube player */
function stop() {
    if (ytplayer) {
        ytplayer.stopVideo();
    }
}

/* clear the video from the player */
function clear() {
    if (ytplayer) {
        ytplayer.clearVideo();
    }
}

/* mute the youtube player */
function mute() {
    if (ytplayer) {
        document.getElementById('mute').src = "http://tau-iplayer.googlecode.com/files/mute.png";
        ytplayer.mute();
    }
}

/* unmute the youtube player */
function unMute() {
    if (ytplayer) {
        document.getElementById('mute').src = "http://tau-iplayer.googlecode.com/files/volume.png";
        ytplayer.unMute();
    }
}

/* get the duration of the played track */
function getDuration() {
	if (ytplayer) {
		return ytplayer.getDuration();
	}
}

/* returns the current time of the played track */
function getCurrTime(){
	if (ytplayer) {
		return ytplayer.getCurrentTime();
	}
}

/* goes to the given time-location in the track */
function seekTo(second) {
    if (ytplayer) {
        ytplayer.seekTo(second, true);
        if(!isPlaying){
        	pause();
        }
    }
}

/* a class which represents a track */
function Track(playlist, title, artist, id, duration, thumbnail, rating, key){
	this.playlist = playlist;
	this.title = title;
	this.artist = artist;
	this.id = id;
	this.duration = duration;
	this.thumbnail = thumbnail;
	this.rating = rating;
	this.key = key;
}

/* a class which represent a transactions between playlists
 * used when a song is move between two playlists
 */
function TrackTransaction(senderID, receiverID, message, when, track, read, key){
	this.senderID = senderID;
    this.receiverID = receiverID;
    this.message = message;
    this.when = when;
    this.track = track;
    this.read = read;
    this.key = key;
}

/* a class which represents a playlist */
function Playlist(name, key){
	this.name = name;
	this.key = key;
}

/* prints a string representations of a track */
function printTrack(track){
	separator = (track.artist.length == 0)? "" : " - ";
	return track.artist + separator + track.title; 
}

/* search youtube for a song */
function searchSong(){
	var r1 = document.getElementById('searchText');
	var t = encodeURI(r1.value);
	var url = "http://gdata.youtube.com/feeds/api/videos?q=" + t + "&orderby=" + ORDER_BY + "&start-index=1&max-results=" + MAX_RESULTS + "&v=2";
	makeGETRequest(url);
}

/* make get request from the given url */
function makeGETRequest(url) {
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	gadgets.io.makeRequest(url, response, params);
}

/* called when a search get request returned */
function response(obj){
	var txt = obj.text;
	txt = txt.replace(/media:title/g, "mediatitle");
	txt = txt.replace(/media:thumbnail/g, "mediathumbnail");
	txt = txt.replace(/yt:videoid/g, "ytvideoid");
	txt = txt.replace(/yt:duration/g, "ytduration");
	txt = txt.replace(/yt:noembed/g, "ytnoembed");
	txt = txt.replace(/yt:private/g, "ytprivate");
	domdata = loadXMLString(txt);
	var entries = domdata.getElementsByTagName("entry");
	var i = 0;
	var j = 0;
	results = new Array();
	for(i=0; i<entries.length; i++){
		entry = entries[i];
		if(isPublic(entry)){
			title = entry.getElementsByTagName("mediatitle")[0].childNodes[0].nodeValue;
			id = entry.getElementsByTagName("ytvideoid")[0].childNodes[0].nodeValue;
			duration = entry.getElementsByTagName("ytduration")[0].getAttribute("seconds");
			thumbnail = entry.getElementsByTagName("mediathumbnail")[0].getAttribute("url");
			results[j] = new Track("", title, "", id, duration, thumbnail, "0", "");
			j++;
		}
	}
	if(addFirstResult){
		setTrack(results[0], currPlaylist.name, results[0].title, results[0].artist)
		postTrack(results[0]);
	}
	displayResults(results);
}

/* checks if the returned track is public and can be played in the player */
function isPublic(entry){
	var privateVid = entry.getElementsByTagName("ytprivate");
	var noembed = entry.getElementsByTagName("ytnoembed");
	if((privateVid.length == 0) && (noembed.length == 0)){
		return true;
	}else{
		return false;
	}
}

/* visualization of the search action */
function searchSongAction(){
	handleTabs(1);
	document.getElementById('searchResults').innerHTML = displayLoading();
	//switchSearchTab = true;
	addFirstResult = false;
	searchSong();
}

/* visualization of the i'm feeling luck search */
function luckyAddSong(){
	if(currPlaylist != null){
		//switchSearchTab = false;
		addFirstResult = true;
		searchSong();
	}else{
		message = "No playlist selected!";
		displayFeedback();
	}
}

/* displays the search results */
function displayResults(results){
	newHTML = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"
	var i=0;
	if(results.length == 0){
		newHTML += "<tr class=\"songListOFF\">";
		newHTML += "<td> Search returned no results </td>";
		newHTML += "</tr>";
	}else{
		for(i=0; i<results.length; i++){
			newHTML +="<tr class=\"songListOFF\" onmouseover=\"this.className=\'songListON\'\" onmouseout=\"this.className=\'songListOFF\'\">";
			newHTML +="<td class=\"tableTD\" onClick=\"showAddSongMenu(results["+i+"]);\">" + results[i].title + "</td>";
			newHTML +="</tr>";
		}
	}
	newHTML = newHTML + "</table>";
	document.getElementById('searchResults').innerHTML = newHTML;
	handleHeight();
}

/* load XML component from a string */
function loadXMLString(txt){
	try //Internet Explorer
	{
	xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc.async="false";
	xmlDoc.loadXML(txt);
	return(xmlDoc);
	}
	catch(e)
	{
	try //Firefox, Mozilla, Opera, etc.
	{
	parser=new DOMParser();
	xmlDoc=parser.parseFromString(txt,"text/xml");
	return(xmlDoc);
	}
	catch(e) {alert(e.message)}
	}
	return(null);
}

/* handles the dynamic height */
function handleHeight(){
	gadgets.window.adjustHeight();
}

/* handles a tab selection */
function handleTabs(tab){
	document.getElementById('communityHL').style.display = "none";
	document.getElementById('searchResultHL').style.display = "none";
	document.getElementById('playlistHeader').style.display = "none";
	document.getElementById('playlists').style.display = "none";
	document.getElementById('searchResults').style.display = "none";
	document.getElementById('community').style.display = "none";
	if(tab == 0){ //clicked on playlist
		document.getElementById('playlists').style.display = "block";
		document.getElementById('playlistLeft').src = "http://tau-iplayer.googlecode.com/files/playlists-left.png";
		document.getElementById('playlistTab').className = "chtab";
		document.getElementById('playlistSearch').src = "http://tau-iplayer.googlecode.com/files/playlists-search.png";
		document.getElementById('searchTab').className = "tab";
		document.getElementById('searchCommunity').src = "http://tau-iplayer.googlecode.com/files/search-community.png";
		document.getElementById('communityTab').className = "tab";
		document.getElementById('communityRight').src = "http://tau-iplayer.googlecode.com/files/community-right.png";
		document.getElementById('playlistHeader').style.display = "block";
	}
	if(tab == 1){ //clicked on search
		document.getElementById('searchResults').style.display = "block";
		document.getElementById('playlistLeft').src = "http://tau-iplayer.googlecode.com/files/Playlists-left.png";
		document.getElementById('playlistTab').className = "tab";
		document.getElementById('playlistSearch').src = "http://tau-iplayer.googlecode.com/files/Playlists-Search2.png";
		document.getElementById('searchTab').className = "chtab";
		document.getElementById('searchCommunity').src = "http://tau-iplayer.googlecode.com/files/Search-Community2.png";
		document.getElementById('communityTab').className = "tab";
		document.getElementById('communityRight').src = "http://tau-iplayer.googlecode.com/files/Community-right.png";
		document.getElementById('searchResultHL').style.display = "block";
	}
	if(tab == 2){ //clicked on community
		document.getElementById('community').style.display = "block";
		document.getElementById('playlistLeft').src = "http://tau-iplayer.googlecode.com/files/Playlists-Left3.png";
		document.getElementById('playlistTab').className = "tab";
		document.getElementById('playlistSearch').src = "http://tau-iplayer.googlecode.com/files/Playlists-Search3.png";
		document.getElementById('searchTab').className = "tab";
		document.getElementById('searchCommunity').src = "http://tau-iplayer.googlecode.com/files/Search-Community3.png";
		document.getElementById('communityTab').className = "chtab";
		document.getElementById('communityRight').src = "http://tau-iplayer.googlecode.com/files/Community-right3.png";
		document.getElementById('communityHL').style.display = "block";
	}
	handleHeight();
}

/* displays the preloader */
function displayLoading(){
	content = '';
	content += '<table width="100%" height="100%">'
	content += '<tr>'
	content += '<td align="center" valign="center">'
	content += '<img src="http://tau-iplayer.googlecode.com/files/loading.gif">'
	content += '</td>'
	content += '</tr>'
	content += '</table>'
	return content;
}

/* visualiztions of the tabs change */
function changeAction(img, action) {
    if (action == 0) { //play and pause
        playPath = "http://tau-iplayer.googlecode.com/files/play.png";
        pausePath = "http://tau-iplayer.googlecode.com/files/pause.png";
        if (img.src == playPath) {
            play();
        }
        else {
            pause();
        }
    }
    if (action == 1) { //volume and mute
        volumePath = "http://tau-iplayer.googlecode.com/files/volume.png";
        mutePath = "http://tau-iplayer.googlecode.com/files/mute.png";
        if (img.src == volumePath) {
            mute();
        }
        else {
            unMute();
        }
    }
    if (action == 2) { //minimize and maximize
        minimizePath = "http://tau-iplayer.googlecode.com/files/minimizeVideo.png";
        maximizePath = "http://tau-iplayer.googlecode.com/files/maximizeVideo.png";
        if (img.src == minimizePath) { //need to minimize
            img.src = maximizePath;
            minimizeVideo();
        } else { // need to maximize;
            img.src = minimizePath;
            maximizeVideo();
        }
    }
}

/* minimazing the youtube player video */
function minimizeVideo() {
    if (ytplayer) {
        ytplayer.style.visibility = "hidden";
        document.getElementById('playing').className = "playingMinimized";
        document.getElementById('thePlayer').className = "thePlayerMinimized";
        handleHeight();
    }
}

/* maximizing the youtube player video */
function maximizeVideo() {
    if (ytplayer) {
        ytplayer.style.visibility = "visible";
        document.getElementById('playing').className = "playingMaximized";
        document.getElementById('thePlayer').className = "thePlayer";
        handleHeight();
    }
}

/* showing or hjiding the tabs (minimizing and maximizing) */
function showHideTabs(){
	if(document.getElementById('dynamicContent').style.display == "none"){
		document.getElementById('contrTabs').src="http://tau-iplayer.googlecode.com/files/minimize.gif";
		document.getElementById('dynamicContent').style.display = "block"
	} else {
		document.getElementById('contrTabs').src="http://tau-iplayer.googlecode.com/files/maximize.png";
		document.getElementById('dynamicContent').style.display = "none";
	}
	handleHeight();
}

document.write('<div id="addSongMenu"></div>');
document.write('<div id="addPlaylistMenu"></div>');
document.write('<div id="renameTrackMenu"></div>');
document.write('<div id="setPlaylistMenu"></div>');
document.write('<div id="shareSongMenu"></div>');
document.write('<div id="incomingSongMenu"></div>');
document.write('<div id="deletePlaylistDialog"></div>');

/* showing the dialog for deleting a playlist */
function showDeletePlaylistDialog(playlist){
	if(playlist != null){
		deleteplaylistdialogobj = document.getElementById("deletePlaylistDialog");
		var windowWidth = ie5? IEcompatTest().clientWidth : window.innerWidth;
		var windowHeight = ie5? IEcompatTest().clientHeight : window.innerHeight;
		content = "<form>";
		content += "<table class=\"menu\" border=\"0\">";
		content += "<tr>";
		content += "<td align=\"center\" valign=\"top\"><b>Are you sure you <br> want to delete " + playlist.name + "? </b></td>";
		content += "</tr>";
		content += "<tr>";
		content += "<td colspan=\"2\" align=\"center\"><input type=\"button\" value=\"OK\" onclick=\"deletePlaylist(currPlaylist); hideDeletePlaylistDialog();\" /><input type=\"button\" value=\"Cancel\" onclick=\"hideDeletePlaylistDialog();\" /></td>";
		content += "</tr>";
		content += "</table>";
		content += "</form>";
		deleteplaylistdialogobj.innerHTML = content;
		var w = deleteplaylistdialogobj.offsetWidth;
		var rightedge = windowWidth*0.5 - w/2;
		var bottomedge = windowHeight*0.65;
		deleteplaylistdialogobj.style.left = rightedge;
		deleteplaylistdialogobj.style.top = bottomedge;
		deleteplaylistdialogobj.style.visibility="visible";
	}
	return false;
}

/* hides the delete playlist dialog */
function hideDeletePlaylistDialog(){
	if (window.deleteplaylistdialogobj)
		deleteplaylistdialogobj.style.visibility="hidden";
}

/* show the menu for reading an incoming message */
function showIncomingSongMenu(trackTransaction){
	incomingTrack = trackTransaction.track;
	markReadTrackTransaction(trackTransaction);
	incomingsongmenuobj = document.getElementById("incomingSongMenu");
	var windowWidth = ie5? IEcompatTest().clientWidth : window.innerWidth;
	var windowHeight = ie5? IEcompatTest().clientHeight : window.innerHeight;
	content = "<form name=\"incomingSongForm\" method=\"post\" action=\"\" onSubmit=\"execAddIncomingSong(incomingTrack); return false;\">";
	content += "<table class=\"menu\" border=\"0\">";
	content += "<tr>";
	content += "<td valign=\"top\"><b>From:</b></td>";
	content += "<td align=\"left\">";
	content += (friends[trackTransaction.senderID] == null)? ("Unknown") : (friends[trackTransaction.senderID]);
	content += "</td>";
	content += "<td rowspan=\"5\"><img id=\"incomingSongIMG\" onload=\"displayIncomingSongMenu();\" src=\"" + trackTransaction.track.thumbnail + "\" align=\"right\" /></td>";
	content += "</tr>";
	content += "<tr>";
	content += "<td valign=\"top\"><b>Title:</b></td>";
	content += "<td valign=\"top\"><input id=\"incomingTrackTitle\" value=\"" + trackTransaction.track.title.replace(/\"/g,"''") + "\"></td>";
	content += "<tr>";
	content += "<td valign=\"top\"><b>Artist:</b></td>";
	content += "<td valign=\"top\"><input id=\"incomingTrackArtist\" value=\"" + trackTransaction.track.artist.replace(/\"/g,"''") + "\"></td>";
	content += "</tr>";
	content += "<tr>";
	content += "<td><b>Playlist:</b></td>";
	content += "<td><select id=\"incomingTrackPlaylist\">";
	for(i=0; i<playlists.length; i++){
		if((currPlaylist != null) && (playlists[i].name == currPlaylist.name)){
			content += "<option selected=\"selected\">" + playlists[i].name + "</option>";
		}else{
			content += "<option>" + playlists[i].name + "</option>";
		}
	}
	content += "</select></td>";
	content += "</tr>";		
	content += "<tr>";
	content += "<td><b>Duration:</b></td>";
	content += "<td>" + getTimeFormat(trackTransaction.track.duration) + "</td>";
	content += "</tr>";
	content += "<tr>";
	content += "<td valign=\"top\"><b>Message:</b></td>";
	content += "<td colspan=\"2\">"
	content += '<textarea readonly="readonly" id="incomingMsg">';
	content += trackTransaction.message.replace(/\"/g,"''");
	content += '</textarea>';
	content += "</td>";
	content += "</tr>";
	content += "<tr>";
	content += "<td colspan=\"3\" align=\"center\"><input type=\"button\" value=\"Add Song\" onclick=\"execAddIncomingSong(incomingTrack);\"/><input type=\"button\" value=\"Preview\" onclick=\"playTrack(incomingTrack);\" /><input type=\"button\" value=\"Close\" onclick=\"hideIncomingSongMenu();\" /></td>";
	content += "</tr>";
	content += "</table>";
	content += "</form>";
	incomingsongmenuobj.innerHTML = content;
	return false;
}

/* displays the menu used to add a song from the inbox */
function displayIncomingSongMenu(){
	incomingsongmenuobj = document.getElementById("incomingSongMenu");
	var windowWidth = ie5? IEcompatTest().clientWidth : window.innerWidth;
	var windowHeight = ie5? IEcompatTest().clientHeight : window.innerHeight;
	
	var w = incomingsongmenuobj.offsetWidth;
	var rightedge = windowWidth*0.5 - w/2;
	var bottomedge = windowHeight*0.43;
	incomingsongmenuobj.style.left = rightedge;
	incomingsongmenuobj.style.top = bottomedge;
	incomingsongmenuobj.style.visibility="visible";
	handleHeight();
}

/* showing the menu for sending a song to a friend */
function showShareSongMenu(track){
	shareTrack = track;
	sharesongmenuobj = document.getElementById("shareSongMenu");
	var windowWidth = ie5? IEcompatTest().clientWidth : window.innerWidth;
	var windowHeight = ie5? IEcompatTest().clientHeight : window.innerHeight;
	content = "<form name=\"shareSongForm\" method=\"post\" action=\"\" onSubmit=\"execPostTrackTransaction(shareTrack); return false;\">";
	content += "<table class=\"menu\" border=\"0\">";
	content += "<tr>";
	content += "<td valign=\"top\"><b>To:</b></td>";
	content += "<td>";
	content += shareSelectContent;
	content += "</td>";
	content += "<td rowspan=\"4\"><img id=\"shareSongIMG\" onload=\"displayShareSongMenu();\" src=\"" + track.thumbnail + "\" align=\"right\" /></td>";
	content += "</tr>";
	content += "<tr>";
	content += "<td valign=\"top\"><b>Title:</b></td>";
	content += "<td valign=\"top\"><input id=\"shareTrackTitle\" readonly=\"readonly\" value=\"" + track.title.replace(/\"/g,"''") + "\"></td>";
	content += "<tr>";
	content += "<td valign=\"top\"><b>Artist:</b></td>";
	content += "<td valign=\"top\"><input id=\"shareTrackArtist\" readonly=\"readonly\" value=\"" + track.artist.replace(/\"/g,"''") + "\"></td>";
	content += "</tr>";		
	content += "<tr>";
	content += "<td><b>Duration:</b></td>";
	content += "<td>" + getTimeFormat(track.duration) + "</td>";
	content += "</tr>";
	content += "<tr>";
	content += "<td valign=\"top\"><b>Message:</b></td>";
	content += "<td colspan=\"2\">"
	content += '<textarea id="sendMsg">';
	content += '</textarea>';
	content += "</td>";
	content += "</tr>";
	content += "<tr>";
	content += "<td colspan=\"3\" align=\"center\"><input type=\"button\" value=\"Send\" onclick=\"execPostTrackTransaction(shareTrack)\" /><input type=\"button\" value=\"Cancel\" onclick=\"hideShareSongMenu();\" /></td>";
	content += "</tr>";
	content += "</table>";
	content += "</form>";
	sharesongmenuobj.innerHTML = content;
	return false;
}

/* displays the menu used to share tracks */
function displayShareSongMenu(){
	sharesongmenuobj = document.getElementById("shareSongMenu");
	var windowWidth = ie5? IEcompatTest().clientWidth : window.innerWidth;
	var windowHeight = ie5? IEcompatTest().clientHeight : window.innerHeight;
	
	var w = sharesongmenuobj.offsetWidth;
	var rightedge = windowWidth*0.5 - w/2;
	var bottomedge = windowHeight*0.43;
	sharesongmenuobj.style.left = rightedge;
	sharesongmenuobj.style.top = bottomedge;
	sharesongmenuobj.style.visibility="visible";
}

/* displays the menu used to add a new playlist or rename an existing one */
function showAddPlaylistMenu(playlist){
	playlstmenuobj = document.getElementById("addPlaylistMenu");
	var windowWidth = ie5? IEcompatTest().clientWidth : window.innerWidth;
	var windowHeight = ie5? IEcompatTest().clientHeight : window.innerHeight;
	content = "<form name=\"addPlaylistForm\" method=\"post\" action=\"\" onSubmit=\"addPlaylist(document.getElementById('addPlaylistName').value); hideAddPlaylistMenu(); return false;\">";
	content += "<table class=\"menu\" border=\"0\">";
	content += "<tr>";
	content += "<td valign=\"top\"><b>Playlist Name:</b></td>";
	inputTxt = (playlist == null) ? "" : playlist.name;
	playlistName = (playlist == null) ? null : ("'" + playlist.name + "'");
	content += "<td valign=\"top\"><input value=\"" + inputTxt + "\" id=\"addPlaylistName\"></td>";
	content += "</tr>";
	content += "<tr><td colspan=\"2\"><div id=\"duplicateName\" style=\"display: none;\">This name aleardy exsists</div></td></tr>";
	content += "<tr>";
	buttonTxt = (playlist == null) ? "Add Playlist" : "Rename";
	content += "<td colspan=\"2\" align=\"center\"><input type=\"button\" value=\"" + buttonTxt + "\" onclick=\"execPlaylistOperation(" + playlistName + ");\" /><input type=\"button\" value=\"Cancel\" onclick=\"hideAddPlaylistMenu();\" /></td>";
	content += "</tr>";
	content += "</table>";
	content += "</form>";
	playlstmenuobj.innerHTML = content;
	var w = playlstmenuobj.offsetWidth;
	var rightedge = windowWidth*0.5 - w/2;
	var bottomedge = windowHeight*0.65;
	playlstmenuobj.style.left = rightedge;
	playlstmenuobj.style.top = bottomedge;
	playlstmenuobj.style.visibility="visible";
	return false;
}

/* removing leading white spaces from a string */
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

/* executes a playlist operation, 
 * whether it is renaming a playlist or adding a new playlist */
function execPlaylistOperation(playlistName){
	var newName = document.getElementById('addPlaylistName').value;
	if(trim(newName).length == 0) return;
	document.getElementById("duplicateName").style.display = "none";
	if(playlistName == null){
		for(i=0; i<playlists.length; i++){
			if(playlists[i].name == newName){
				document.getElementById("duplicateName").style.display = "block";
				return;
			}
		}
		hideAddPlaylistMenu();
		addPlaylist(newName);
	}else{
		hideAddPlaylistMenu();
		renamePlaylist(playlistName, newName);
	}
}

/* making a playlisr rename */
function renamePlaylist(playlistName, newName){
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
	req.send(handleRenamePlaylist(playlistName, newName));
}

/* handles the rename playlist operation according to the 
 * given playlist name and new playlist name */
function handleRenamePlaylist(playlistName, newName){
	return function(data){
		var user = data.get('viewer').getData();
		var params = {};
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST
		var url = 'http://tau-iplayer.appspot.com';
		post_data = gadgets.io.encodeValues({
			'action' : "renamePlaylist",
			'userID' : user.getId(),
			'prevName' : playlistName,
			'newName' : newName });
        params[gadgets.io.RequestParameters.POST_DATA] = post_data;
		currPlaylist.name = newName;
		gadgets.io.makeRequest(url, loadPlaylists, params);
		message = "Renaming playlist: " + playlistName;
		displayFeedback();
	}
}

/* hides the add or rename playlist menu */
function hideAddPlaylistMenu(){
	if (window.playlstmenuobj)
		playlstmenuobj.style.visibility="hidden";
}

/* showing the menu for renaming a track */
function showRenameTrackMenu(track){
	changeTrack = track;
	renametrackmenuobj = document.getElementById("renameTrackMenu");
	var windowWidth = ie5? IEcompatTest().clientWidth : window.innerWidth;
	var windowHeight = ie5? IEcompatTest().clientHeight : window.innerHeight;
	content = "<form name=\"renameTrackForm\" method=\"post\" action=\"\" onSubmit=\"renameTrack(changeTrack, document.getElementById('renameTitle').value, document.getElementById('renameArtist').value); hideRenameTrackMenu(); return false;\">";
	content += "<table class=\"menu\" border=\"0\">";
	content += "<tr>";
	content += "<td valign=\"top\"><b>Title:</b></td>";
	content += "<td valign=\"top\"><input id=\"renameTitle\" value=\"" + track.title.replace(/\"/g,"''") + "\"></td>";
	content += "</tr>";
	content += "<tr>";
	content += "<td valign=\"top\"><b>Artist:</b></td>";
	content += "<td valign=\"top\"><input id=\"renameArtist\" value=\"" + track.artist.replace(/\"/g,"''") + "\"></td>";
	content += "</tr>";
	content += "<tr>";
	content += "<td colspan=\"2\" align=\"center\"><input type=\"button\" value=\"OK\" onclick=\"renameTrack(changeTrack, document.getElementById('renameTitle').value, document.getElementById('renameArtist').value); hideRenameTrackMenu();\" /><input type=\"button\" value=\"Cancel\" onclick=\"hideRenameTrackMenu();\" /></td>";
	content += "</tr>";
	content += "</table>";
	content += "</form>";
	renametrackmenuobj.innerHTML = content;
	var w = renametrackmenuobj.offsetWidth;
	var rightedge = windowWidth*0.5 - w/2;
	var bottomedge = windowHeight*0.65;
	renametrackmenuobj.style.left = rightedge;
	renametrackmenuobj.style.top = bottomedge;
	renametrackmenuobj.style.visibility="visible";
	return false;
}

/* hides the rename track menu */
function hideRenameTrackMenu(){
	if (window.renametrackmenuobj)
		renametrackmenuobj.style.visibility="hidden";
}

/* showing the menu for setting the playlist */
function showSetPlaylistMenu(track){
	changeTrack = track;
	setplaylstmenuobj = document.getElementById("setPlaylistMenu");
	var windowWidth = ie5? IEcompatTest().clientWidth : window.innerWidth;
	var windowHeight = ie5? IEcompatTest().clientHeight : window.innerHeight;
	content = "<form name=\"setPlaylistForm\" method=\"post\" action=\"\" onSubmit=\"changeTrackPlaylist(changeTrack, document.getElementById('setPlaylistSelect').options[document.getElementById('setPlaylistSelect').selectedIndex].text); hideSetPlaylistMenu(); return false;\">";
	content += "<table class=\"menu\" border=\"0\">";
	content += "<tr>";
	content += "<td><b>Playlist:</b></td>";
	content += "<td><select id=\"setPlaylistSelect\">";
	for(i=0; i<playlists.length; i++){
		content += "<option>" + playlists[i].name + "</option>";
	}
	content += "</select></td>";
	content += "</tr>";
	content += "<tr>";
	content += "<td colspan=\"2\" align=\"center\"><input type=\"button\" value=\"OK\" onclick=\"changeTrackPlaylist(changeTrack, document.getElementById('setPlaylistSelect').options[document.getElementById('setPlaylistSelect').selectedIndex].text); hideSetPlaylistMenu();\" /><input type=\"button\" value=\"Cancel\" onclick=\"hideSetPlaylistMenu();\" /></td>";
	content += "</tr>";
	content += "</table>";
	content += "</form>";
	setplaylstmenuobj.innerHTML = content;
	var w = setplaylstmenuobj.offsetWidth;
	var rightedge = windowWidth*0.5 - w/2;
	var bottomedge = windowHeight*0.65;
	setplaylstmenuobj.style.left = rightedge;
	setplaylstmenuobj.style.top = bottomedge;
	setplaylstmenuobj.style.visibility="visible";
	return false;
}

/* hides the set track's playlist menu */
function hideSetPlaylistMenu(){
	if (window.setplaylstmenuobj)
		setplaylstmenuobj.style.visibility="hidden";
}

/* add a new playlist with the name playlistName */
function addPlaylist(playlistName){
	var playlist = new Playlist(playlistName, "");
	postPlaylist(playlist);
	currPlaylist = playlist;
}

/* showing the menu for adding a song */
function showAddSongMenu(track){
	addTrack = track;
	addsongmenuobj = document.getElementById("addSongMenu");
	var windowWidth = ie5? IEcompatTest().clientWidth : window.innerWidth;
	var windowHeight = ie5? IEcompatTest().clientHeight : window.innerHeight;
	content = "<form name=\"addSongForm\" method=\"post\" action=\"\" onSubmit=\"execAddSong(addTrack); return false;\">";
	content += "<table class=\"menu\" border=\"0\">";
	content += "<tr>";
	content += "<td valign=\"top\"><b>Title:</b></td>";
	content += "<td valign=\"top\"><input id=\"addTrackTitle\" value=\"" + track.title.replace(/\"/g,"''") + "\"></td>";
	content += "<td rowspan=\"4\"><img id=\"songIMG\" onload=\"displayAddSongMenu();\" src=\"" + track.thumbnail + "\" align=\"right\" /></td>";
	content += "</tr>";
	content += "<tr>";
	content += "<td valign=\"top\"><b>Artist:</b></td>";
	content += "<td valign=\"top\"><input id=\"addTrackArtist\" value=\"" + track.artist.replace(/\"/g,"''") + "\"></td>";
	content += "</tr>";		
	content += "<tr>";
	content += "<td><b>Playlist:</b></td>";
	content += "<td><select id=\"addTrackPlaylist\">";
	for(i=0; i<playlists.length; i++){
		if((currPlaylist != null) && (playlists[i].name == currPlaylist.name)){
			content += "<option selected=\"selected\">" + playlists[i].name + "</option>";
		}else{
			content += "<option>" + playlists[i].name + "</option>";
		}
	}
	content += "</select></td>";
	content += "</tr>";
	content += "<tr>";
	content += "<td><b>Duration:</b></td>";
	content += "<td>" + getTimeFormat(track.duration) + "</td>";
	content += "</tr>";
	content += "<tr>";
	content += "<td colspan=\"3\" align=\"center\"><input type=\"button\" value=\"Add Song\" onclick=\"execAddSong(addTrack);\" /><input type=\"button\" value=\"Preview\" onclick=\"playPreviewTrack(addTrack);\" /><input type=\"button\" value=\"Cancel\" onclick=\"hideAddSongMenu();\" /></td>";
	content += "</tr>";
	content += "</table>";
	content += "</form>";
	addsongmenuobj.innerHTML = content;
	return false;
}

/* executes adding a song operation */
function execAddSong(track){
	prepareAddTrack(track); 
	postTrack(track); 
	hideAddSongMenu();
}

/* executes adding a song from inbox operation */
function execAddIncomingSong(track){
	prepareAddIncomingTrack(track); 
	postTrack(track); 
	hideIncomingSongMenu();
}

/* sends a track transaction */
function execPostTrackTransaction(track){
	var receiverID = document.getElementById('selectFriend').options[document.getElementById('selectFriend').selectedIndex].value;
	var message = document.getElementById('sendMsg').value;
	trackTransaction = new TrackTransaction("", receiverID, message, "", track, "unread");
	postTrackTransaction(trackTransaction);
	hideShareSongMenu();
}

/* set the transaction between playlists */
function setTrackTransaction(trackTransaction, senderID, receiverID, message, when, track, read){
	trackTransaction.senderID = senderID;
	trackTransaction.receiverID = receiverID;
	trackTransaction.message = message;
	trackTransaction.when = when;
	trackTransaction.track = track;
	trackTransaction.read = read;
}

/* reading the transaction from the server */
function markReadTrackTransaction(trackTransaction){
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	post_data = gadgets.io.encodeValues({
		'action' : "markReadTrackTransaction",
		'key' : trackTransaction.key });
	params[gadgets.io.RequestParameters.POST_DATA] = post_data;
	var url ='http://tau-iplayer.appspot.com';
	gadgets.io.makeRequest(url, uploadTimeTrackTransaction(), params);
}

function isRead(trackTransaction){
	return (trackTransaction.read == "read");
}

/* displays the menu used to add a song */
function displayAddSongMenu(){
	addsongmenuobj = document.getElementById("addSongMenu");
	var windowWidth = ie5? IEcompatTest().clientWidth : window.innerWidth;
	var windowHeight = ie5? IEcompatTest().clientHeight : window.innerHeight;
	
	var w = addsongmenuobj.offsetWidth;
	var rightedge = windowWidth*0.5 - w/2;
	var bottomedge = windowHeight*0.54;
	addsongmenuobj.style.left = rightedge;
	addsongmenuobj.style.top = bottomedge;
	addsongmenuobj.style.visibility="visible";
}

function prepareAddTrack(track){
	track.rating = "0";
	var title = document.getElementById('addTrackTitle').value;
	var artist = document.getElementById('addTrackArtist').value;
	var playlist = document.getElementById('addTrackPlaylist').options[document.getElementById('addTrackPlaylist').selectedIndex].text;
	setTrack(track, playlist, title, artist);
}

function prepareAddIncomingTrack(track){
	track.rating = "0";
	var title = document.getElementById('incomingTrackTitle').value;
	var artist = document.getElementById('incomingTrackArtist').value;
	var playlist = document.getElementById('incomingTrackPlaylist').options[document.getElementById('incomingTrackPlaylist').selectedIndex].text;
	setTrack(track, playlist, title, artist);
}

/* checks compatabilty with IE */
function IEcompatTest(){
	return (document.compatMode && document.compatMode.indexOf("CSS")!=-1)? document.documentElement : document.body;
}

/* hides the add song menu */
function hideAddSongMenu(){
	if (window.addsongmenuobj)
		addsongmenuobj.style.visibility="hidden";
}

/* hides the share song menu */
function hideShareSongMenu(){
	if (window.sharesongmenuobj)
		sharesongmenuobj.style.visibility="hidden";
}

/* hides the add incoming song menu */
function hideIncomingSongMenu(){
	if (window.incomingsongmenuobj)
		incomingsongmenuobj.style.visibility="hidden";
}

/* init the iplayer
 * called onload
 */
function init(){
	loadPlaylists();
	loadCommunity();
	loadFriends();
	displayTopSongs("world");
	handleHeight();
	handleTabs(0);
	prefs = new gadgets.Prefs();
	if((trim(prefs.getString("playlist")).length != 0)){
		loadPlaylistFromPrefs();
	}
}

/*
 * loading the playlist
 */
function postPlaylist(playlist){
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
	req.send(handlePostPlaylist(playlist));
}

/* sending the track transation to the server */
function postTrackTransaction(trackTransaction){
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
	req.send(handlePostTrackTransaction(trackTransaction));
}

/* handles the post track transaction operation according to the given track
 * transaction */
function handlePostTrackTransaction(trackTransaction){
	return function(response){
		var senderID = response.get('viewer').getData().getId();
		var params = {};
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
		post_data = gadgets.io.encodeValues({
			'action' : "addTrackTransaction",
			'senderID' : senderID,
			'receiverID' : trackTransaction.receiverID,
			'message' : trackTransaction.message,
			'track_key' : trackTransaction.track.key,
			'read' : trackTransaction.read });
		params[gadgets.io.RequestParameters.POST_DATA] = post_data;
		var url ='http://tau-iplayer.appspot.com';
		gadgets.io.makeRequest(url, function(){}, params);
		message = "Sending track: " + printTrack(trackTransaction.track);
		displayFeedback();
	}
}

/* handles the post playlist operation 
 * according to the given playlist */
function handlePostPlaylist(playlist) {
	return function(data){
		var user = data.get('viewer').getData();
		var userID = user.getId();
		message = null;
		var params = {};
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
		post_data = gadgets.io.encodeValues({
			'action' : "addPlaylist",
			'userID' : userID,
			'name' : playlist.name });
        params[gadgets.io.RequestParameters.POST_DATA] = post_data;
        var url = 'http://tau-iplayer.appspot.com';
            
        gadgets.io.makeRequest(url, uploadTimePlaylist(), params);
        message = "Adding playlist: " + playlist.name;
        displayFeedback();
	}
}

function uploadTimePlaylist(){
	setTimeout("loadPlaylists()", 250);
}

/*
 * loading a track
 */
function postTrack(track){
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
	req.send(handlePostTrack(track));
}

/* handles the post track operation according to the given track */
function handlePostTrack(track) {
	return function(data){
		var user = data.get('viewer').getData();
		var userID = user.getId();
		addTrack = track;
		message = "Added: \"" + printTrack(track) + "\"";
		var params = {};
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
		post_data = gadgets.io.encodeValues({
			'action' : "add",
			'userID' : userID,
			'playlist' : track.playlist,
			'title' : track.title,
            'artist' : track.artist,
            'id' : track.id,
            'duration' : track.duration,
            'thumbnail' : track.thumbnail,
            'rating' : track.rating });
        params[gadgets.io.RequestParameters.POST_DATA] = post_data;
        var url = 'http://tau-iplayer.appspot.com';
            
        gadgets.io.makeRequest(url, uploadTime(), params);
	}
}

/* deletes the given track transaction */
function deleteTrackTransaction(trackTransaction){
	var params = {};
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	post_data = gadgets.io.encodeValues({
		'action' : "deleteTrackTransaction",
		'key' : trackTransaction.key });
    params[gadgets.io.RequestParameters.POST_DATA] = post_data;
    var url = 'http://tau-iplayer.appspot.com';
        
    gadgets.io.makeRequest(url, uploadTimeTrackTransaction(), params);
}

/* deletes the given playlist */
function deletePlaylist(playlist){
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
	req.send(handleDeletePlaylist(playlist));
}

/* handles the delete playlist operation */
function handleDeletePlaylist(playlist){
	return function(data){
		var user = data.get('viewer').getData();
		var userID = user.getId();
		var params = {};
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
		post_data = gadgets.io.encodeValues({
			'action' : "deletePlaylist",
			'userID' : userID,
			'playlist' : playlist.name });
	    params[gadgets.io.RequestParameters.POST_DATA] = post_data;
	    var url = 'http://tau-iplayer.appspot.com';
	    currPlaylist = null;  
	    gadgets.io.makeRequest(url, uploadTimePlaylist(), params);
	    message = "Deleting playlist: " + playlist.name;
	    displayFeedback();
	}
}

/* deletes the given track */
function deleteTrack(track){
	
	if (trackEqual(playedTrack,track)){
		stop();
		playNextTrack();
	}
	message = "Deleted: \"" + printTrack(track) + "\"";
	var params = {};
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	post_data = gadgets.io.encodeValues({
		'action' : "delete",
		'key' : track.key });
    params[gadgets.io.RequestParameters.POST_DATA] = post_data;
    var url = 'http://tau-iplayer.appspot.com';
        
    gadgets.io.makeRequest(url, uploadTime(), params);
}

/* update track info */
function updateTrack(track, reload){
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
	req.send(handleUpdateTrack(track, reload));
}

/* handles the update track operation. reload indicates whether tracks 
 * need to reload after update */
function handleUpdateTrack(track, reload) {
	return function(data){
		var user = data.get('viewer').getData();
		var userID = user.getId();
		addTrack = null;
		var params = {};
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
		post_data = gadgets.io.encodeValues({
			'action' : "update",
			'userID' : userID,
			'playlist' : track.playlist,
			'title' : track.title,
            'artist' : track.artist,
            'id' : track.id,
            'duration' : track.duration,
            'thumbnail' : track.thumbnail,
            'rating' : track.rating,
            'key' : track.key });
        params[gadgets.io.RequestParameters.POST_DATA] = post_data;
        var url = 'http://tau-iplayer.appspot.com';
        
        if(reload){    
        	gadgets.io.makeRequest(url, uploadTime(), params);
        }else{
        	gadgets.io.makeRequest(url, function() {}, params);
        }
	}
}

function uploadTime(){
	setTimeout("loadTracks()", 250);
}

function uploadTimeTrackTransaction(){
	setTimeout("loadFriends()", 250);
}

function loadCommunity(){
	loadTopTracks("world");
}

/* load the user friends */
function loadFriends(){
	var idspec = opensocial.newIdSpec({ "userId" : "VIEWER", "groupId" : "FRIENDS" });
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), "viewer");
    req.add(req.newFetchPeopleRequest(idspec), "viewerFriends");
	req.send(onLoadFriends);
}

/* displays the inbox of incoming track transactions */
function displayInbox(){
	document.getElementById('topSongs').style.display = "none";
	document.getElementById('communityHeader').innerHTML = "Inbox";
	document.getElementById('inbox').innerHTML = displayLoading();
	document.getElementById('inbox').style.display = "block";
	loadFriends();
}

/* displays the top 20 tracks in the data store. 
 * type indicates whether to show, world top 20 or friends top 20. */
function displayTopSongs(type){
	document.getElementById('inbox').style.display = "none";
	document.getElementById('communityHeader').innerHTML = getTopMenu();
	var x = document.getElementById("TopSelection");
	var i = 0;
	if(type == "world")
		i = 0;
	if(type == "friends")
		i = 1;
	x.options[i].selected = true;
	document.getElementById('topSongs').innerHTML = displayLoading();
	document.getElementById('topSongs').style.display = "block";
	loadTopTracks(type);
}

/* a response for the get request on loading the friends */
function onLoadFriends(data){
	var viewer = data.get('viewer').getData();
	var viewerFriends = data.get('viewerFriends').getData();
	friends = new Array();
	shareSelectContent =  "<select id=\"selectFriend\">";
	viewerFriends.each(function(person){
		friends[person.getId()] = person.getDisplayName();
		shareSelectContent += '<option value = "' + person.getId() + '">' + friends[person.getId()] + "</option>";
	});
	shareSelectContent += '</select>';
	loadTrackTransactions(viewer, friends);
}

function loadPlaylists(){
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
	req.send(handleLoadPlaylists());
}

/* handles the load playlist operation */
function handleLoadPlaylists(){
	return function(data){
		var user = data.get('viewer').getData();
		var params = {};
		params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
		var url = 'http://testIplayer.appspot.com/?nocache='+new Date().getTime() +'&action=getPlaylists' + '&userID=' + user.getId();
		
		gadgets.io.makeRequest(url, onLoadPlaylists, params);
	}
}

/* a response for the get request for loading the playlist */
function onLoadPlaylists(response){
	playlists = new Array();
	playlists = response.data;
	initDropMenu();
	document.getElementById('playlists').innerHTML = "";
	if(currPlaylist != null){
		document.getElementById(currPlaylist.name).selected = true;
		handlePlaylistSelection();
	}
	if(playlists.length == 0){
		isHelp = false;
		showHideHelp();
	} else {
		isHelp = true;
		showHideHelp();
	}
}

/* loading the top tracks */
function loadTopTracks(type){
	var idspec = opensocial.newIdSpec({ "userId" : "VIEWER", "groupId" : "FRIENDS" });
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), "viewer");
    req.add(req.newFetchPeopleRequest(idspec), "viewerFriends");
	req.send(handleLoadTopTracks(type));
}

/* handles the load top 20 tracks operation according to the given type,
 * which indicates whether to get the friends top 20 songs or 
 * the world top 20 songs */
function handleLoadTopTracks(type){
	return function(data){
		var viewer = data.get('viewer').getData();
		var viewerFriends = data.get('viewerFriends').getData();
		friends = new Array();
		shareSelectContent = "<select id=\"selectFriend\">";
		var params = {};
		params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
		var url = 'http://testIplayer.appspot.com/?nocache='+new Date().getTime() +'&action=getTopTracks&type='+ type + '&userID0=' + viewer.getId();
		n = 0;
		viewerFriends.each(function(person){
			n++;
			url += ('&userID' + n + '=' + person.getId());
			friends[person.getId()] = person.getDisplayName();
			shareSelectContent += '<option value = "' + person.getId() + '">' + friends[person.getId()] + "</option>";
		});
		shareSelectContent += '</select>';
		url += ('&n=' + (n+1));
		gadgets.io.makeRequest(url, onLoadTopTracks, params);
	}
}

/* a response for the ger request of loading the top tracks */
function onLoadTopTracks(response){
	topTracks = new Array();
	topTracks = response.data;
	
	newHTML = "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\">";
	var i=0;
	for(i=0; i<topTracks.length; i++){
		newHTML += "<tr id=\"topTrack"+i+"\" onclick=\"showAddSongMenu(topTracks[" + i + "])\" class=\"songListOFF\" onmouseover=\"this.className=\'songListON\'\" onmouseout=\"this.className=\'songListOFF\'\">";
		newHTML += "<td class=\"tableTD\">" + (i+1) + ".&nbsp;" + "</td>";
		newHTML += "<td class=\"tableTD\">" + printTrack(topTracks[i]) + "</td>";
		newHTML += "<td class=\"tableTD\">" + getRatingDisplay(parseFloat(topTracks[i].rating)) + "</td>";
		newHTML += "</tr>";
	}
	newHTML = newHTML + "</table>";
	document.getElementById('topSongs').innerHTML = newHTML;
	
	handleHeight();
}

/* displaying the rating of a song */
function getRatingDisplay(rating){
	var display = "";
	
	display += '<div class="rating_bar">'
	display += '<div style="width:' + Math.round((rating/5)*100) + '%"></div>'
	display += '</div>'
	
	return display;
}

/* loading the tracks */
function loadTracks(){
	var req = opensocial.newDataRequest();
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
	req.send(handleLoadTracks());
}

/* handles the load tracks operation */
function handleLoadTracks(){
	return function(data){
		var user = data.get('viewer').getData();
		var params = {};
		params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
		if(currPlaylist != null){
			var url = 'http://testIplayer.appspot.com/?nocache='+new Date().getTime() +'&action=getTracks' + '&userID=' + user.getId() + '&playlist=' + encodeURI(currPlaylist.name);			
			gadgets.io.makeRequest(url, onLoadTracks, params);
		}else{
			if(message != null) displayFeedback();
		}
	}
}

/* highlights the current track playing */
function displayTrackChoice(){
	for(i=0; i<tracks.length; i++){
		if((playedTrack != null) && trackEqual(tracks[i], playedTrack)){
			document.getElementById("track"+i).setAttribute((document.all ? 'className' : 'class'), "songListON");
		}else{
			document.getElementById("track"+i).setAttribute((document.all ? 'className' : 'class'), "songListOFF");
		}
	}
}

/* returns true iff the tracks a equal */
function trackEqual(track1, track2){
	if(track1 != null && track2 != null){
		return (track1.key == track2.key)
	} else {
		return false
	}
}

/* setting the rating for a song */
function setRating(track, rating){
	track.rating = rating;
	updateTrack(track, true);
}

/* loading a transaction of tracks */
function loadTrackTransactions(viewer, friends){
	var url = 'http://testIplayer.appspot.com/?nocache='+new Date().getTime() +'&action=getTrackTransactions' + '&receiverID=' + viewer.getId();
	gadgets.io.makeRequest(url, onLoadTracksReceived(friends));
}

/* returns the date in a specific format */
function getDateFormat(date){
	var split = date.split("-");
	var dateFormat = split[2] + '/' + split[1] + '/' + split[0];
	return dateFormat;
}

/* response which is called when a message comes */
function onLoadTracksReceived(friends){
	return function(response){
		numNewIncomingTracks = 0;
		inbox = new Array();
		results = gadgets.json.parse(response.data);
		newHTML = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
		for(var i=0; i<results.length; i++){
			var senderID = results[i].senderID;
			var receiverID = results[i].receiverID;
			var message = results[i].message;
			var when = getDateFormat(results[i].when.substring(0,10));
			var track_title = results[i].track_title;
			var track_artist = results[i].track_artist;
			var track_id = results[i].track_id;
			var track_duration = results[i].track_duration;
			var track_thumbnail = results[i].track_thumbnail;
			var track = new Track("", track_title, track_artist, track_id, track_duration, track_thumbnail, "0", "");
			var read = results[i].read;
			var key = results[i].key;
			var recvTrack = new TrackTransaction(senderID, receiverID, message, when, track, read, key);
			inbox[i] = recvTrack;
			var className = "";
			if(!isRead(recvTrack)){
				numNewIncomingTracks++;
				className = "unreadTrack";
			}else{
				className = "readTrack";
			}
			newHTML += "<tr id=\"recvTrack"+i+"\" class=\"" + className + "\" onmouseover=\"this.className=\'songListON\'\" onmouseout=\"this.className=\'" + className + "\'\">";
			newHTML += (friends[inbox[i].senderID] == null)? ("<td valign=\"top\" class=\"tableTD\" onclick=\"showIncomingSongMenu(inbox[" + i + "])\" width=\"25%\"> Unknown </td>") : ("<td valign=\"top\" class=\"tableTD\" onclick=\"showIncomingSongMenu(inbox[" + i + "])\" width=\"25%\">" + friends[inbox[i].senderID] + "</td>");
			newHTML += "<td class=\"tableTD\" onclick=\"showIncomingSongMenu(inbox[" + i + "])\" width=\"60%\">" + printTrack(inbox[i].track) + "</td>";
			newHTML += "<td valign=\"top\" class=\"tableTD\" onclick=\"showIncomingSongMenu(inbox[" + i + "])\" width=\"10%\">" + inbox[i].when + "</td>";;
			newHTML += "<td class=\"tableTD\" onclick=\"deleteTrackTransaction(inbox["+i+"])\" width=\"5%\"><img src=\"http://tau-iplayer.googlecode.com/files/delete2.png\" align=\"right\" /></td>";
			newHTML += "</tr>";
		}
		newHTML += "</table>";
		document.getElementById('inboxGoTo').innerHTML = "Inbox (" + numNewIncomingTracks + ")";
		document.getElementById('inbox').innerHTML = newHTML;
		handleHeight();
	}
}

/* response for the get request of loading playlist tracks */
function onLoadTracks(response){
	prefs = new gadgets.Prefs();
	tracks = new Array();
	tracks = response.data;
	tracks.sort(sortTracks);
	
	newHTML = "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\">";
	var i=0;
	for(i=0; i<tracks.length; i++){
		newHTML += "<tr id=\"track"+i+"\" class=\"songListOFF\" onmouseover=\"this.className=\'songListON\'\" onmouseout=\"displayTrackChoice();\">";
		newHTML += "<td class=\"tableTD\" onclick=\"playNotPreviewTrack(tracks[" + i + "]);\" width=\"80%\">" + printTrack(tracks[i]) + "</td>";
		newHTML += "<td class=\"tableTD\" width=\"5%\" onClick=\"showmenu(event, '150px', "+i+")\" onMouseout=\"delayhidemenu()\"><img src=\"http://tau-iplayer.googlecode.com/files/arrow.gif\" align=\"center\" /></td>";
		newHTML += "<td class=\"tableTD\" width=\"10%\">";
		
		newHTML += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" onmouseout=\"displayTrackRating(tracks["+i+"]," + i + ")\">";
		newHTML += "<tr>";
		newHTML += "<td onmouseover=\"displayRating(1," + i + ")\" onclick=\"setRating(tracks["+i+"], 1)\">";
		newHTML += "<img id=\"one"+i+"\" src=\"http://tau-iplayer.googlecode.com/files/rating_off.gif\" align=\"center\" />";
		newHTML += "</td>";
		newHTML += "<td onmouseover=\"displayRating(2," + i + ")\" onclick=\"setRating(tracks["+i+"], 2)\">";
		newHTML += "<img id=\"two"+i+"\" src=\"http://tau-iplayer.googlecode.com/files/rating_off.gif\" align=\"center\" />";
		newHTML += "</td>"; 
		newHTML += "<td onmouseover=\"displayRating(3," + i + ")\" onclick=\"setRating(tracks["+i+"], 3)\">";
		newHTML += "<img id=\"three"+i+"\" src=\"http://tau-iplayer.googlecode.com/files/rating_off.gif\" align=\"center\" />";
		newHTML += "</td>";
		newHTML += "<td onmouseover=\"displayRating(4," + i + ")\" onclick=\"setRating(tracks["+i+"], 4)\">";
		newHTML += "<img id=\"four"+i+"\" src=\"http://tau-iplayer.googlecode.com/files/rating_off.gif\" align=\"center\" />";
		newHTML += "</td>";
		newHTML += "<td onmouseover=\"displayRating(5," + i + ")\" onclick=\"setRating(tracks["+i+"], 5)\">";
		newHTML += "<img id=\"five"+i+"\" src=\"http://tau-iplayer.googlecode.com/files/rating_off.gif\" align=\"center\" />";
		newHTML += "</td>";
		newHTML += "</tr>";
		newHTML += "</table>";
		
		newHTML += "</td>";
		newHTML += "<td class=\"tableTD\" width=\"5%\"><img src=\"http://tau-iplayer.googlecode.com/files/delete2.png\" align=\"right\" onclick=\"deleteTrack(tracks["+i+"]);\" /></td>";
		newHTML += "</tr>";
	}
	newHTML = newHTML + "</table>";
	document.getElementById('playlists').innerHTML = newHTML;
	
	if(message != null) displayFeedback();
	displayTrackChoice();
	initRating();
	if(firstLoad){
		prefs.set("playlist", currPlaylist.name);
		firstLoad = false;
	} 
	handleHeight();
}

/* initializing the rating for songs from the server */
function initRating(){
	for(i=0; i<tracks.length; i++){
		displayTrackRating(tracks[i],i);
	}
}

/* displays the rating for a track with stars */
function displayRating(rating, trackNum){
	document.getElementById("one"+trackNum).src="http://tau-iplayer.googlecode.com/files/rating_off.gif";
	document.getElementById("two"+trackNum).src="http://tau-iplayer.googlecode.com/files/rating_off.gif";
	document.getElementById("three"+trackNum).src="http://tau-iplayer.googlecode.com/files/rating_off.gif";
	document.getElementById("four"+trackNum).src="http://tau-iplayer.googlecode.com/files/rating_off.gif";
	document.getElementById("five"+trackNum).src="http://tau-iplayer.googlecode.com/files/rating_off.gif";
	switch(rating){
		case 5:
		document.getElementById("five"+trackNum).src="http://tau-iplayer.googlecode.com/files/rating_on.gif";
		case 4:
		document.getElementById("four"+trackNum).src="http://tau-iplayer.googlecode.com/files/rating_on.gif";
		case 3:
		document.getElementById("three"+trackNum).src="http://tau-iplayer.googlecode.com/files/rating_on.gif";
		case 2:
		document.getElementById("two"+trackNum).src="http://tau-iplayer.googlecode.com/files/rating_on.gif";
		case 1:
		document.getElementById("one"+trackNum).src="http://tau-iplayer.googlecode.com/files/rating_on.gif";
	}
}

/* displays the rating of the given track */
function displayTrackRating(track, trackNum){
	rating = parseInt(track.rating);
	displayRating(rating, trackNum);
}

/* sorting the array of tracks by name */
function sortTracks(track0, track1){
	str0 = printTrack(track0).toUpperCase();
	str1 = printTrack(track1).toUpperCase();
	
	if(str0 == str1){
		return 0;
	}
	var arr = new Array(2);
	arr[0] = str0;
	arr[1] = str1;
	arr.sort();
	if(arr[0] == str0){
		return -1;
	}else{
		return 1;
	} 
}

/* updating a track infoi */
function setTrack(track, playlist, title, artist){
	track.playlist = playlist;
	track.title = title;
	track.artist = artist;
}

/* initializing the playlists select box */
function initDropMenu(){
	var x = document.getElementById("playlistHL");
	document.getElementById("playlistHL").innerHTML = "";
	var op1 = document.createElement('option');
	var op2 = document.createElement('option');
	op1.value = "select";
	op2.value = "add";
	op1.text =  "Select Playlist";
	op2.text =  "New...";
	try{
	  x.add(op1,null); // standards compliant
	  x.add(op2,null); 
	}catch(ex){
	  x.add(op1); // IE only
	  x.add(op2); 
	}
	for(i=0; i<playlists.length; i++){
		addPlaylistToMenu(playlists[i]);
	}
}

/* adds playlist to the playlist selection menu */
function addPlaylistToMenu(playlist){
	var x = document.getElementById("playlistHL");
	var y = document.createElement('option');
	y.text = playlist.name;
	y.id = playlist.name;
	addOption = x.length-1;
	try{
		var sel = x.options[addOption];
	 	x.add(y,sel); // standards compliant
	}catch(ex){
	  	x.add(y,addOption); // IE only
	}
}

/* loading the last playlist which the user listened to
 * from the user prefs
 */
function loadPlaylistFromPrefs(){
	prefs = new gadgets.Prefs();
	currPlaylist = new Playlist(prefs.getString("playlist"), "");
	message = null;
	if(prevPlaylist != currPlaylist){
		document.getElementById('playlists').innerHTML = displayLoading();
		loadTracks();
	}
}

/* handles the top 20 type selection */
function handleTopSelection(){
	var x = document.getElementById("TopSelection");
	var type = x.options[x.selectedIndex].value;
	displayTopSongs(type);
}

/* update the playlist in the user prefs */
function updatePlaylistState(playlist){
	prefs = new gadgets.Prefs();
	prefs.set("playlist", playlist.name);
}

/* handles the playlist selection event */
function handlePlaylistSelection(){
	var x = document.getElementById("playlistHL");
	if(x.options[x.selectedIndex].value == "add"){
		showAddPlaylistMenu(null);
		if(currPlaylist != null){
			document.getElementById(currPlaylist.name).selected = true;
		}else{
			x.options[0].selected = true;
		}
	}else{
		if(x.options[x.selectedIndex].value != "select"){
			var prevPlaylist = currPlaylist;
			currPlaylist = new Playlist(x.options[x.selectedIndex].text, "");
			updatePlaylistState(currPlaylist);
			message = null;
			if(prevPlaylist != currPlaylist){
				document.getElementById('playlists').innerHTML = displayLoading();
				loadTracks();
			}
		}else{
			if(currPlaylist != null){
				document.getElementById(currPlaylist.name).selected = true;
			}
		}
	}
}

/* chages the track's playlist to the given playlist */
function changeTrackPlaylist(track, playlist){
	setTrack(track, playlist, track.title, track.artist);
	updateTrack(track, true);
}

/* rename the track */
function renameTrack(track, title, artist){
	setTrack(track, track.playlist, title, artist);
	updateTrack(track, true);
}

document.write('<div id="popitmenu" onMouseover="clearhidemenu();" onMouseout="dynamichide(event)"></div>');

function showmenu(e, optWidth, i){
	var defaultMenuWidth="150px" //set default menu width.
	if (!document.all&&!document.getElementById)
		return;
	clearhidemenu();
	menuobj = ie5? document.all.popitmenu : document.getElementById("popitmenu");
	var content;
	
	content = '<a href="javascript: void(0)" onclick="showRenameTrackMenu(tracks['+i+']); hidemenu();">Rename</a>'
	content += '<a href="javascript: void(0)" onclick="showSetPlaylistMenu(tracks['+i+']); hidemenu();">Move</a>'
	content += '<a href="javascript: void(0)" onclick="showShareSongMenu(tracks['+i+']); hidemenu();">Share</a>'
	menuobj.innerHTML = content;
	menuobj.style.width = (typeof optWidth!="undefined")? optWidth : defaultMenuWidth;
	menuobj.contentwidth=menuobj.offsetWidth;
	menuobj.contentheight=menuobj.offsetHeight;
	eventX = ie5? event.clientX : e.clientX;
	eventY = ie5? event.clientY : e.clientY;
	//Find out how close the mouse is to the corner of the window
	var rightedge=ie5? IEcompatTest().clientWidth-eventX : window.innerWidth-eventX;
	var bottomedge=ie5? IEcompatTest().clientHeight-eventY : window.innerHeight-eventY;
	//if the horizontal distance isn't enough to accomodate the width of the context menu
	if (rightedge < menuobj.contentwidth)
		//move the horizontal position of the menu to the left by it's width
		menuobj.style.left=ie5? IEcompatTest().scrollLeft+eventX-menuobj.contentwidth+"px" : window.pageXOffset+eventX-menuobj.contentwidth+"px";
	else
		//position the horizontal position of the menu where the mouse was clicked
		menuobj.style.left=ie5? IEcompatTest().scrollLeft+eventX+"px" : window.pageXOffset+eventX+"px";
	//same concept with the vertical position
	if (bottomedge<menuobj.contentheight)
		menuobj.style.top=ie5? IEcompatTest().scrollTop+eventY-menuobj.contentheight+"px" : window.pageYOffset+eventY-menuobj.contentheight+"px";
	else
		menuobj.style.top=ie5? IEcompatTest().scrollTop+event.clientY+"px" : window.pageYOffset+eventY+"px";
	menuobj.style.visibility="visible";
	return false;
}

function contains_ns6(a, b) {
	while (b.parentNode)
		if ((b = b.parentNode) == a)
			return true;
	return false;
}

function hidemenu(){
	if (window.menuobj)
		menuobj.style.visibility="hidden";
}

function dynamichide(e){
	if (ie5&&!menuobj.contains(e.toElement))
		hidemenu();
	else if (ns6&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget, e.relatedTarget))
		hidemenu();
}

/* hides menu after delay */
function delayhidemenu(){
	delayhide = setTimeout("hidemenu()",500);
}

function clearhidemenu(){
	if (window.delayhide)
		clearTimeout(delayhide);
}

/* handels the time bar events */
function handleEventTimeBar(event) {
    var timeBarStart = document.body.clientWidth - 144;
    seek = event.clientX - timeBarStart;
    seekTo((seek / 144) * getDuration());
    document.getElementById('timeBarTD').style.width = seek + "px";
    document.getElementById('timeBarTD').style.visibility = "visible";
}

/* handles the progress-bar */
function handleTimeBar() {
    var duration = getDuration();
    var currTime = getCurrTime();
    var width = (144 / duration) * currTime;
    document.getElementById('timeBarTD').style.visibility = "visible";
    if ((currTime > 0) && (isPlaying))
        document.getElementById('timeBarTD').style.width = width + "px";
}

var currHelpId;
/* showing a songle help subject */
function showSingleHelp(id){
	document.getElementById("openPlaylistHelp").style.display = "none";
	document.getElementById("searchHelp").style.display = "none";
	document.getElementById("addSongHelp").style.display = "none";
	document.getElementById("enjoyHelp").style.display = "none";
	if(id==0){
		if(currHelpId != 10){
			document.getElementById("openPlaylistHelp").style.display = "block";
			currHelpId = 10;
		}
		else {
			document.getElementById("openPlaylistHelp").style.display = "none";
			currHelpId = 0;
		}
	} else if(id==1){
		if(currHelpId != 11){
			document.getElementById("searchHelp").style.display = "block";
			currHelpId = 11;
		}
		else {
			document.getElementById("searchHelp").style.display = "none";
			currHelpId = 1;
		}
	} else if(id==2){
		if(currHelpId != 12){
			document.getElementById("addSongHelp").style.display = "block";
			currHelpId = 12;
		}
		else {
			document.getElementById("addSongHelp").style.display = "none";
			currHelpId = 2;
		}
	} else {
		if(currHelpId != 13){
			document.getElementById("enjoyHelp").style.display = "block";
			currHelpId = 13;
		}
		else {
			document.getElementById("enjoyHelp").style.display = "none";
			currHelpId = 3;
		}
	}
	handleHeight();
}

/* returns the HTML representation of the Top 20 menu */
function getTopMenu(){
	content = '<select onchange="handleTopSelection();" class="header" id="TopSelection">';
	content += '<option value="world">World</option>';
	content += '<option value="friends">Friends</option>';
	content += '</select>';
	return content;					
}

var isHelp = false;
/* showing the help window */
function showHideHelp(){
	if(isHelp){
		document.getElementById("easyStart").style.display = "none";
		isHelp = false;
	} else {
		document.getElementById("easyStart").style.display = "block";
		isHelp = true;
	}
	handleHeight();
}

if (gadgets.util != null){
	gadgets.util.registerOnLoadHandler(init);
}else {
	var html = 'The gadgets.* API is not available.<br>Check out the <a href="http://www.google.com/ig/sandbox" target="_blank">iGoogle developer sandbox</a>.';
	document.getElementById('nowPlayinName').innerHTML = html;
}